import React from 'react';
import { Form, Row, Col, Select, Input, InputNumber } from 'antd';
import enums from '@/enums';
import Area from './Area';
import AcceptanceNameInput, { parseAcceptanceNameStr, toAcceptanceNameStr } from '../controls/AcceptanceNameInput';
import { useCloudRegionOptions } from '../../../ResourceImportTasks/hooks';
import { useCheckAcceptanceNameUniqueness } from '../hooks';
import { useProvinceOptions } from '../../hooks';

const LABEL_WIDTH = 140; // 标签宽度

/**
 * 基本信息区域
 */
function BasicArea(props) {
    const { edit, initialValues } = props;

    const { getFieldValue, setFieldValue, setFieldsValue, validateFields } = Form.useFormInstance();
    const disabled = edit && initialValues.acceptanceStatus.includes('IN_PROGRESS');

    const cloudRegionOptions = useCloudRegionOptions();
    const checkAcceptanceNameUniqueness = useCheckAcceptanceNameUniqueness();
    const provinceOptions = useProvinceOptions();

    const renderNormalSelect = (props) => {
        return <Select allowClear showSearch optionFilterProp="label" placeholder="请选择" {...props} />;
    };

    const items = [
        {
            label: '云区域',
            name: 'cloudRegionCode',
            rules: [{ required: true, message: '必选' }],
            children: renderNormalSelect({
                disabled,
                loading: cloudRegionOptions.loading,
                options: cloudRegionOptions.data,
                onChange(value) {
                    const cloudRegionName = value
                        ? cloudRegionOptions.data.find((option) => option.value === value).label
                        : undefined;
                    const [_, phase, batch] = parseAcceptanceNameStr(getFieldValue('acceptanceMaterialName'));

                    setFieldsValue({
                        cloudRegionName,
                        acceptanceMaterialName: toAcceptanceNameStr(cloudRegionName, phase, batch),
                        deviceList: undefined,
                    });
                    validateFields(['acceptanceMaterialName', 'deviceList']);
                },
            }),
        },
        {
            colSpan: 0,
            noStyle: true,
            name: 'cloudRegionName',
            children: <></>,
        },
        {
            colSpan: 16,
            label: '验收资料名称',
            name: 'acceptanceMaterialName',
            rules: [
                {
                    async validator(_, value) {
                        const parts = parseAcceptanceNameStr(value);

                        if (parts.every((part) => part)) {
                            try {
                                if (edit && value === initialValues.acceptanceMaterialName) return Promise.resolve();

                                return (await checkAcceptanceNameUniqueness.runAsync(value))
                                    ? Promise.resolve()
                                    : Promise.reject('名称重复');
                            } catch (err) {
                                return Promise.reject('校验失败');
                            }
                        }

                        return Promise.reject('必填');
                    },
                },
            ],
            children: <AcceptanceNameInput style={{ width: 500 }} disabled={disabled} />,
        },
        {
            label: '资源归属省分',
            name: 'provinceCode',
            rules: [{ required: true, message: '必选' }],
            children: renderNormalSelect({
                loading: provinceOptions.loading,
                options: provinceOptions.data,
                onChange(value) {
                    const provinceName = value
                        ? provinceOptions.data.find((option) => option.value === value).label
                        : undefined;
                    setFieldValue('cloudRegionProvinceName', provinceName);
                },
            }),
        },
        {
            colSpan: 0,
            noStyle: true,
            name: 'cloudRegionProvinceName',
            children: <></>,
        },
        {
            label: '资源池类型',
            name: 'cloudRegionType',
            rules: [{ required: true, message: '必选' }],
            children: renderNormalSelect({
                options: enums.ossAcceptance.poolTypes.options(),
            }),
        },
        {
            label: '申请类型',
            name: 'applyType',
            rules: [{ required: true, message: '必选' }],
            children: renderNormalSelect({
                options: enums.ossAcceptance.applyTypes.options(),
            }),
        },
        {
            label: '资源池架构',
            name: 'cloudArchitecture',
            children: renderNormalSelect({
                options: enums.ossAcceptance.poolArchs.options(),
            }),
        },
        {
            noStyle: true,
            dependencies: ['applyType'],
            children: ({ getFieldValue }) => (
                <Form.Item
                    dependencies={['applyType']}
                    labelCol={{ flex: `${LABEL_WIDTH}px` }}
                    label="软件版本"
                    name="softwareVersion"
                    rules={[{ required: getFieldValue('applyType') === 'establishment', message: '必填' }]}
                >
                    <Input autoComplete="off" placeholder="请输入" />
                </Form.Item>
            ),
        },
        {
            label: '存储类型',
            name: 'storageType',
            children: renderNormalSelect({
                options: enums.ossAcceptance.storageTypes.options(),
            }),
        },
        {
            label: '对象存储编码方式',
            name: 'objectStorageCode',
            children: <Input autoComplete="off" placeholder="请输入" />,
        },
        {
            label: '是否有等保安全设备',
            name: 'isSecurityDevices',
            children: renderNormalSelect({
                options: enums.ossAcceptance.booleans.options(),
            }),
        },
        {
            noStyle: true,
            dependencies: ['applyType'],
            children: ({ getFieldValue }) => (
                <Form.Item
                    dependencies={['applyType']}
                    labelCol={{ flex: `${LABEL_WIDTH}px` }}
                    label="资源池网络出口带宽"
                    name="cloudNetOutBandwidth"
                    validateFirst
                    rules={[
                        { required: getFieldValue('applyType') === 'establishment', message: '必填' },
                        { validator: (_, value) => (value === '0' ? Promise.reject('不能为0') : Promise.resolve()) },
                    ]}
                >
                    <InputNumber
                        style={{ width: '100%' }}
                        controls={false}
                        min={0}
                        stringMode
                        addonAfter="Mb/s"
                        placeholder="请输入"
                    />
                </Form.Item>
            ),
        },
    ];

    const renderItem = (props, index) => {
        const { colSpan = 8 } = props;

        return (
            <Col key={props.name ?? index} span={colSpan}>
                <Form.Item labelCol={{ flex: `${LABEL_WIDTH}px` }} {...props} />
            </Col>
        );
    };

    return (
        <Area style={{ overflow: 'hidden' }} title="基本信息" required>
            <Row gutter={60}>{items.map(renderItem)}</Row>
        </Area>
    );
}

export default BasicArea;
